package net.leesrobots.data.sink;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 数据源
 */
public class DataSource {
    /**
     *
     */
    private ComboPooledDataSource cpds;

    /**
     * 构造函数
     * @throws IOException
     * @throws SQLException
     * @throws PropertyVetoException
     */
    public DataSource(String url, String user, String password) throws IOException, SQLException, PropertyVetoException {
        cpds = new ComboPooledDataSource();
        cpds.setDriverClass("com.mysql.jdbc.Driver");
        cpds.setJdbcUrl(url);
        cpds.setUser(user);
        cpds.setPassword(password);

        cpds.setMinPoolSize(10);
        cpds.setAcquireIncrement(5);
        cpds.setMaxPoolSize(50);
        cpds.setInitialPoolSize(20);
        cpds.setMaxStatements(0);
        cpds.setMaxIdleTime(25000);

        cpds.setNumHelperThreads(10);
        cpds.setAutoCommitOnClose(true);
        cpds.setPreferredTestQuery("SHOW PROCESSLIST");
        cpds.setIdleConnectionTestPeriod(60);
        cpds.setCheckoutTimeout(30000);
    }

    /**
     * 获得数据连接
     * @return 数据连接
     * @throws SQLException
     */
    public Connection getConnection() throws SQLException {
        return this.cpds.getConnection();
    }

    /**
     * 关闭
     */
    public void close() {
        cpds.close();
    }
}
